package com.njit.mailm.core.controller;

import com.njit.mailm.commmon.constant.MailConstant;
import com.njit.mailm.commmon.utils.GUID;
import com.njit.mailm.commmon.utils.MailUtil;
import com.njit.mailm.core.bean.*;
import com.njit.mailm.core.service.DraftService;
import com.njit.mailm.core.service.MailService;
import com.njit.mailm.core.service.SendService;
import com.njit.mailm.core.service.UploadService;
import com.sun.mail.pop3.POP3Folder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.Message;
import javax.mail.Store;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 写邮件控制器
 *
 * @author Administrator
 */
@RequestMapping("/mail")
@Controller
public class MailController {

    @Autowired
    private MailService mailService;

    @Autowired
    private DraftService draftService;

    @Autowired
    private SendService sendservice;
    @Autowired
    private UploadService uploadService;
    /**
     * 显示发送页
     */
    @RequestMapping(value = "/compose", method = RequestMethod.GET)
    public String compose(Model model,HttpSession session ,String id) {
//        System.out.println(id);
        if(id == null || id.isEmpty()){
            id = GUID.getGUID();
            model.addAttribute("draftId", id);
        }else{
            model.addAttribute("draftId",id);
            Draft draft = draftService.getDraftById(id);
            model.addAttribute("draft",draft);
        }

        //获取当前用户的所有email列表
        User user = (User) session.getAttribute(MailConstant.CURRENTUSER);
        List<Email>  emails= mailService.getEmailsByUser(user);
        model.addAttribute("emails",emails);
        return "mailCompose";
    }

    /**
     * 发送邮件
     */
    @ResponseBody
    @RequestMapping(value = "/compose", method = RequestMethod.POST)
    public boolean compose(MessageWrap msg,String draftId)  {
        //设置email
        msg.setEmail( mailService.getEmailById(msg.getEmail().getId()));
        msg.setTos(msg.getTo().split(";"));
        if(!msg.getCopyTo().isEmpty()){
            msg.setCcs(msg.getCopyTo().split(";"));
        }
        if(!msg.getBcc().isEmpty()){
            msg.setBccs(msg.getBcc().split(";"));
        }

        try {
            sendservice.sendHtmlEmail(msg,draftId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 发送包含附件的邮件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendAttachmentMail" ,method = RequestMethod.POST)
    public boolean sendAttachmentMail(){
        return false;
    }

    @RequestMapping(value = "/read", method = RequestMethod.POST)
    public String readMail(String id, Model model) {
        model.addAttribute("messageDetail", mailService.selectMessageById(id));
        return "mailRead";
    }

    /**
     * 从数据库中取出数据，显示
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(String controller) {
        if(controller.equals("inbox")){
            return "forward:../list/listReceive.shtml";
        }else if(controller.equals("starBox")){
            return "forward:../list/listStar.shtml";
        }else if(controller.equals("trashBox")){
            return "forward:../list/listTrash.shtml";
        }else if(controller.equals("draftBox")) {
            return "forward:../list/listDraft.shtml";
        }
        return "error";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String mailIndex(HttpSession session,Model model,String id) {
        if(id != null){
            Email email = mailService.getEmailById(id);
            session.setAttribute(MailConstant.CURRENTEMAIL,email);
        }
        if(session.getAttribute(MailConstant.CURRENTUSER) == null){
            return "redirect:../login.shtml";
        }

        Email email = (Email) session.getAttribute(MailConstant.CURRENTEMAIL);
        if(email == null){
            List<Email> emails = mailService.getEmailsByUser((User) session.getAttribute(MailConstant.CURRENTUSER));
            if(emails.size() > 0){
                email = emails.get(0);
            }

        }
        if(email != null){
            session.setAttribute(MailConstant.CURRENTEMAIL,email);
        }

       // model.addAttribute("controller","inbox");


        return "mailbox";
    }


    @RequestMapping(value = "/synchron", method = RequestMethod.GET)
    public String synchron(HttpSession session) {
        try {
            Email email = (Email) session.getAttribute("currentEmail");
            mailService.synchrMail(email);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "forward:list.shtml?page=1";
    }


    @RequestMapping(value = "/bindMail", method = RequestMethod.GET)
    public String showBindMail() {
        return "bindMail";
    }

    @RequestMapping(value = "/bindMail", method = RequestMethod.POST)
    public String bindMail(Email email, HttpSession session) {
        System.out.println(mailService.bindMail(email));
        User user = (User) session.getAttribute(MailConstant.CURRENTUSER);
        email.setUser(user);
        if (mailService.bindMail(email)) {

            mailService.insertMail(email);
        }
        return "redirect:/mail/index.shtml";
    }

    @RequestMapping(value = "/boxList", method = RequestMethod.GET)
    public String boxList(HttpSession session, Model model) {
        Email email = (Email) session.getAttribute(MailConstant.CURRENTEMAIL);
        List<Email> emails = mailService.getEmailsByUser((User) session.getAttribute(MailConstant.CURRENTUSER));
        if(email == null && emails.size() > 0){
            email = emails.get(0);
        }
        session.setAttribute(MailConstant.CURRENTEMAIL, email);
        if (emails != null) {

            model.addAttribute("emails", emails);
        }
        return "boxList";
    }

    @RequestMapping(value="/changeBox",method = RequestMethod.GET)
    public String changeBox(String id,HttpSession session){
        Email email = mailService.getEmailById(id);
        session.setAttribute(MailConstant.CURRENTEMAIL,email);
        return "redirect:index.shtml?page=1";
    }


    /**
     * 获得需要同步的总数量
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getSynchronTotal", method = RequestMethod.GET)
    public Map<String,Object> getSynchronTotal(HttpSession session){
        Email email = (Email) session.getAttribute(MailConstant.CURRENTEMAIL);
        List<Message> messages = mailService.getSynchronMessages(email);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("totalNumber",messages.size());
//        map.put("synchronMessages",messages);
        session.setAttribute("synchronMessage",messages);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "batchSynchron" ,method = RequestMethod.POST)
    public Map<String,Object> batchSynchron(HttpSession session){
        List<Message> synchronMessages = (List<Message>) session.getAttribute("synchronMessage");
        List<Message> batchList = null;
        List<Message> subList = null;
        int totalNumber = 0;
        if(synchronMessages.size( ) > MailConstant.SYNCHRONMAILNUMBER){
            batchList = synchronMessages.subList(0, MailConstant.SYNCHRONMAILNUMBER);
            subList = synchronMessages.subList(MailConstant.SYNCHRONMAILNUMBER,synchronMessages.size());
            totalNumber = subList.size();
        }else{
            batchList = synchronMessages;
            subList = new ArrayList<Message>();
        }

        Email email = (Email) session.getAttribute(MailConstant.CURRENTEMAIL);

        Map<String, Object> storeFolder = mailService.batchSynchron(batchList, email);

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("totalNumber",totalNumber);
        session.setAttribute("synchronMessage",subList);
        if(totalNumber == 0){
            Store store = (Store) storeFolder.get("store");
            POP3Folder inbox = (POP3Folder) storeFolder.get("folder");
            mailService.colseFolder(store,inbox);
        }
        return map;
    }

    @ResponseBody
        @RequestMapping(value = "intervalSynchron",method = RequestMethod.POST)
    public Map<String,Object> intervalSynchron(HttpSession session){
        User user = (User) session.getAttribute(MailConstant.CURRENTUSER);
        List<Email> emails = mailService.getEmailsByUser(user);
        return mailService.intervalSynchron(emails);

    }

}
